package net.sppan.base.task;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import net.sppan.base.common.RedisKey;
import net.sppan.base.config.redis.RedisTemplateUtil;
import net.sppan.base.entity.ContentExuser;
import net.sppan.base.entity.ContentUnreviewed;
import net.sppan.base.entity.DyuserBlocked;
import net.sppan.base.entity.ExContentView;
import net.sppan.base.entity.ExuserContent;
import net.sppan.base.entity.UsertTask;
import net.sppan.base.service.IContentExuserService;
import net.sppan.base.service.IContentUnreviewedService;
import net.sppan.base.service.IDyuserBlockedService;
import net.sppan.base.service.IExuserContentService;
import net.sppan.base.service.IUserService;
import net.sppan.base.service.specification.SimpleSpecificationBuilder;
import net.sppan.base.service.specification.SpecificationOperator.Operator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;



@Component
@Configuration
@EnableScheduling
public class DistributionJob {
private static Logger logger = LoggerFactory.getLogger(DistributionJob.class);
	
	/**
	 * 老的分配表
	 */
	@Autowired
	private IExuserContentService contentService;
	@Autowired
	private IContentUnreviewedService contentUnreviewedService;
	@Autowired
	private IUserService userService; 
	@Autowired
	private RedisTemplateUtil redisTemplateUtil;
	/**
	 * 新分配表
	 */
	@Autowired
	private IContentExuserService contentExuserService;
	@Autowired
	private IDyuserBlockedService dyuserBlockedService;
	/**
	 * 去除定时分配
	 */
//	@Scheduled(fixedRate = 3000000)
	public void findusertesk() {
		List<UsertTask> usertTasks = contentService.findExuserContentList("0");
		Integer taskCount = contentUnreviewedService.countTask("0,3"); 
		taskCount= taskCount>=20000?20000:taskCount; 
		logger.info("需要分配的用户数:"+usertTasks.size() +"待分配审核的帖子数:"+taskCount +"如果总分配数大于20000则只取20000分配" );
		Map<Long, Integer> map=allocationTaskNum(usertTasks, taskCount);
		for (Entry<Long, Integer> entry : map.entrySet()) {
			if(entry.getValue()>0 && taskCount>0){
					Page<ContentUnreviewed> page=contentUnreviewedService.findContentTask("0,3",new PageRequest(0, entry.getValue(), new Sort(Direction.DESC, "uploadDate")));
				     if(page.getSize()>0){
				    	 List<Long> contentIds= new ArrayList<Long>();
				    	 List<ExuserContent> exuserContents=new ArrayList<ExuserContent>();
				    	 for(ContentUnreviewed contentUnreviewed:page.getContent()){
				    		 ExuserContent exuserContent =new ExuserContent();
				    		 exuserContent.setExuserId(entry.getKey());
				    		 exuserContent.setExResult("0");
				    		 exuserContent.setDyContentId(contentUnreviewed.getDyContentId());
				    		 contentIds.add(contentUnreviewed.getDyContentId());
				    		 exuserContents.add(exuserContent);
					     }
				    	 contentUnreviewedService.updateList(contentIds, "1");
				    	 contentService.inserList(exuserContents);
				     }
			}
		}
	}
	  
	
	/**
	 * 任务分配
	 * @param usertTasks
	 * @param taskCount
	 * @return
	 */
	public Map<Long, Integer> allocationTaskNum(List<UsertTask> usertTasks, Integer taskCount) {
		int rev_num = usertTasks.size();// 审核人员总数
		String[][] rev_task = new String[rev_num][3];
		List<Integer> rdList = new ArrayList<>();
		rdList.removeAll(rdList);
		for (UsertTask usertTask : usertTasks) {
			rdList.add(usertTask.getExUserId().intValue());
		}
		logger.info("算法前的任务分配：");
		for (int i = 0; i < rev_num; i++) {
			rev_task[i][0] = String.valueOf(rdList.get(i));
			rev_task[i][1] = String.valueOf(usertTasks.get(i).getIncompleteTaskNum());
			rev_task[i][2] = "0";
			logger.info("审核用户ID,名下剩余未审核任务数: "+rev_task[i][0] + ", " + rev_task[i][1] + " ");
		}
		AlgorithmUtils.taskAllocation(taskCount, rev_num, rev_task);// 调用算法工具类
		logger.info("算法后的任务分配：");
		Map<Long, Integer> map =new HashMap<Long, Integer>();
		for (int i = 0; i < rev_num; i++) {
			map.put(Long.valueOf(rev_task[i][0]), Integer.valueOf(rev_task[i][2]));
			logger.info("审核用户ID,平均分配后任务数,即将分配任务条数"+rev_task[i][0] + "," + rev_task[i][2] + " ");
		}
		return map;
	}
	
	@Scheduled(fixedRate = 180000)
	public void pullTask(){
		SimpleSpecificationBuilder<ContentUnreviewed> builder = new SimpleSpecificationBuilder<ContentUnreviewed>();
		
		builder.add("contentType", Operator.in.name(), "3,4");
//		builder.add("urlAvailable", Operator.eq.name(), "1");
		builder.add("isApproved",  Operator.eq.name(), "3"); 
		builder.add("allotStatus",  Operator.eq.name(), "0"); 
		Page<ContentUnreviewed> page = contentUnreviewedService.findAll(builder.generateSpecification(),new PageRequest(0, 500, new Sort(Direction.DESC, "dyContentId")));
		if(!page.getContent().isEmpty()&&page.getContent()!=null){
			List<Long> ids = new ArrayList<Long>();
			List<ContentExuser> contentExusers=new ArrayList<ContentExuser>();
			for(ContentUnreviewed entity:page.getContent()){
				ContentExuser contentExuser =new ContentExuser();
				contentExuser.setDyContentId(entity.getDyContentId());
				contentExuser.setPublisherDyId(entity.getPublisherDyId());
				contentExuser.setPublisherDyName("");
				contentExuser.setContentType(entity.getContentType());
				contentExuser.setUploadDate(entity.getUploadDate());
				contentExuser.setContentText(entity.getContentText());
				contentExuser.setContentUrl(entity.getContentUrl());
				contentExuser.setPixelHeight(entity.getPixelHeight());
				contentExuser.setPixelWidth(entity.getPixelWidth());
				contentExuser.setIsApproved(entity.getIsApproved());
				contentExuser.setVideoDisplay(entity.getVideoDisplay());
				contentExuser.setInputTime(new Date());

				SimpleSpecificationBuilder<DyuserBlocked> builderBlocked = new SimpleSpecificationBuilder<DyuserBlocked>();
				builderBlocked.add("dyId",Operator.eq.name(), entity.getPublisherDyId());
				Page<DyuserBlocked> page2=dyuserBlockedService.findAll(builderBlocked.generateSpecification(),new PageRequest(0, 1, new Sort(Direction.DESC, "createTime")));
				if(page2.getTotalElements()>0){
					List<DyuserBlocked>  dyuserBlockeds = page2.getContent();
					Date date =new Date();
					if(!dyuserBlockeds.get(0).getBlockedType().equals("0")){//非正常 用戶  
						if(date.before(dyuserBlockeds.get(0).getBlockedEndtime())||dyuserBlockeds.get(0).getBlockedTimeType().equals("4")){
							contentExuser.setExResult("3");
							contentExuser.setExDesc("系统导入自动处理为 不通过");
							//同时设置为 帖子为不通过
							entity.setIsApproved("2");
							contentUnreviewedService.update(entity);
						}else{
							contentExuser.setExResult("0");
						}
					}else{
						contentExuser.setExResult("0");
					} 
				}else{
					contentExuser.setExResult("0");
				}
				contentExusers.add(contentExuser);
				ids.add(entity.getDyContentId());
			}
			contentExuserService.saveList(contentExusers);
			contentUnreviewedService.updateList(ids, "1");
		}
	}
	
	
	
	/**
	 * 将以前分配的任务 导入到新的任务表中   重新进行设置为未分配  
	 */
//	@Scheduled(fixedRate = 300000)
	public synchronized void distributionHis() {
		Page<ExContentView> page= contentService.findExuserContentListHis(new PageRequest(0, 20000, null));
		if(page.getSize()>0 ){
			List<ExuserContent> listIds=new ArrayList<ExuserContent>();
			List<ContentExuser> contentExusers =new ArrayList<ContentExuser>();
			for(ExContentView exContentView:page.getContent()){
				ContentExuser contentExuser=new ContentExuser();
				contentExuser.setDyContentId(exContentView.getDyContentId());
				contentExuser.setPublisherDyId(exContentView.getPublisherDyId());
				contentExuser.setPublisherDyName("");
				contentExuser.setContentType(exContentView.getContentType());
				contentExuser.setUploadDate(exContentView.getUploadDate());
				contentExuser.setContentText(exContentView.getContentText());
				contentExuser.setContentUrl(exContentView.getContentUrl());
				contentExuser.setIsApproved(exContentView.getIsApproved());
				contentExuser.setVideoDisplay(exContentView.getVideoDisplay());
				if(exContentView.getExResult()!=null&&!exContentView.getExResult().equals("0")){
					contentExuser.setInputTime(exContentView.getExTime());
					contentExuser.setAllotTime(exContentView.getExTime());
					contentExuser.setExTime(exContentView.getExTime());
					contentExuser.setExuserId(exContentView.getExuserId());
					contentExuser.setExResult(exContentView.getExResult());
					contentExuser.setOperationCode(UUID.randomUUID().toString());
					contentExuser.setSysStatus("1");
				}else{
					contentExuser.setInputTime(new Date());
					contentExuser.setSysStatus(null);
				}
				
				ExuserContent exuserContent =new ExuserContent();
				exuserContent.setId(exContentView.getId());
				listIds.add(exuserContent);
				contentExusers.add(contentExuser);
			}
			logger.info("########## 新增到新的审核表"+contentExusers.size());
			contentExuserService.saveList(contentExusers);
			logger.info("########## 删除删除旧的审核表数据"+listIds.size());
			contentService.delete(listIds);
		}
	}
	
	/**
	 * 将以前分配的任务 导入到新的任务表中   重新进行设置为未分配  
	 */
	@Scheduled(fixedRate = 600000)
	public void againDistribution(){
		logger.info("######开始重置30 分钟内未审核任务");
		SimpleSpecificationBuilder<ContentExuser> builder = new SimpleSpecificationBuilder<ContentExuser>();
		//分配时间比当前时间小于30分钟 的未审核任务 设置为 未分配 等待重新分配
		Calendar nowAfter = Calendar.getInstance();
		nowAfter.add(Calendar.MINUTE, -30);
		builder.add("allotTime", Operator.lessThanOrEqualTo.name(), nowAfter.getTime());
		builder.add("exResult", Operator.eq.name(), "0");
		List<ContentExuser> contentExusers =contentExuserService.findList(builder.generateSpecification(),new Sort(Direction.DESC,"allotTime"));
		if(!contentExusers.isEmpty()&&contentExusers.size()>0){
			for(ContentExuser contentExuser:contentExusers){//重新设置为待分配
				//防止已审核 进行拉回 先查询是否已经审核
				ContentExuser contentExuserEx= contentExuserService.find(contentExuser.getId());
				if(contentExuserEx.getExResult().equals("0")){
					if(contentExuser.getExdyId()!=null){
					      redisTemplateUtil.del(RedisKey.last_red_key+contentExuser.getExdyId());
					}
					contentExuser.setAllotTime(null);
					contentExuser.setExuserId(null);
					contentExuser.setExdyId(null);
					contentExuserService.update(contentExuser);
				}
			} 
		}
	}
}
